import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';

import '../../net/lf_api_url.dart';
import '../../res/strings/lf_strings.dart';
import '../../widgets/dialog_action_tip.dart';

toChangeEmail() {
  Get.toNamed(LFRoute.pathChangeEmail);
}

class LfChangeEmailLogic extends GetxController {
  LfAuthService authService = Get.find();
  RxString newEmail = "".obs;
  RxString password = "".obs;
  RxString confirmEmail = "".obs;

  TextEditingController emailTextEditingController = TextEditingController();
  TextEditingController confirmEmailTextEditingController =
      TextEditingController();
  TextEditingController passwordTextEditingController = TextEditingController();
  final FocusNode emailFocusNode = FocusNode();
  final FocusNode confirmEmailFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();

  bool get enableContinue =>
      newEmail.value.isEmail &&
      password.value.length >= 6 &&
      confirmEmail.value.isEmail &&
      (confirmEmail.value == newEmail.value);

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    emailTextEditingController.dispose();
    confirmEmailTextEditingController.dispose();
    passwordTextEditingController.dispose();
    emailFocusNode.dispose();
    confirmEmailFocusNode.dispose();
    passwordFocusNode.dispose();
    super.onClose();
  }

  void changeEmail() {
    showLoading();
    LfDio.instance.post<LfBoolEntity>(url: apiChangeEmail, params: {
      "email": newEmail.value,
      "password": password.trim(),
    }).then((value) {
      hideLoading();
      showActionTips(
        tips: "Email update successfully!",
        showCancel: false,
        dismissible: false,
        actionButtonTip: strOK.tr,
        action: () {
          authService.loginOut();
        },
      );
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }
}
